package com.atguigu.gmall.payment.alipay.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.entity.OrderInfo;
import com.atguigu.gmall.mq.service.RabbitService;
import com.atguigu.gmall.payment.alipay.confg.properties.AlipayProperties;
import com.atguigu.gmall.payment.alipay.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    AlipayProperties alipayProperties;

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    OrderFeignClient orderFeignClient;

    @Autowired
    RabbitService rabbitService;

    @Override
    public String getAlipayHtml(Long orderId) throws AlipayApiException {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId).getData();
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderInfo.getOutTradeNo();
        //付款金额，必填
        String total_amount = orderInfo.getTotalAmount().toString();
        //订单名称，必填
        String subject = "尚品会-"+orderInfo.getOutTradeNo();
        //商品描述，可空
        String body = orderInfo.getTradeBody();
        Map<String, String> params = new HashMap<>();
        params.put("total_amount",total_amount);
        params.put("out_trade_no", out_trade_no);
        params.put("subject", subject);
        params.put("body", body);
        params.put("time_expire", DateUtil.formatDate(orderInfo.getExpireTime(),"yyyy-MM-dd HH:mm:ss"));
        params.put("product_code", "FAST_INSTANT_TRADE_PAY");

        alipayRequest.setBizContent(JSONs.objecttoString(params));

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();



        return result;
    }

}
